<?php
    session_start();
    
    //creat short name for variable
    $name=$_POST['name'];
    $password=$_POST['password'];

    if((!isset($name)) || (!isset($password))) {
    // user needs to enter a name and password
?>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>User Login</title>
</head>
<body>
    <form method="post" action="" >
    <table border="0" cellpadding="8" width="350" align="center">
    <tr><td colspan="2" align="center" class="alert"></td></tr>
    <tr><td>Username</td>
       <td><input name="name" type="text" id="username" class="textinput"></td>
    </tr>
    <tr><td>Password</td>
       <td><input name="password" type="password" id="password" class="textinput"></td>
    </tr>
    <tr><td colspan="2"align="center">
       <input type="submit" class="btn" value="Submit">
        </td>
    </tr>
    </table>
    </form>
</body>
</html>
<?php
    }else {
     //connect to mysql
     $mysql=mysqli_connect("localhost","root","");
     if(!$mysql) {
         echo "Cannot connect to db.";
         exit;
     }
     //select the appropriate db
     $selected= mysqli_select_db($mysql,"auth");
     if(!$selected) {
         echo "Cannot select db.";
         exit;
     }
     //query the db to see if there is a record which matches
     $query = "select count(*) from authorized_users where
                name='".$name."' and password=sha1('".$password."')";

    $result=mysqli_query($mysql,$query);
    if(!$result) {
        echo "Cannot run query.";
        exit;
    }
    $row=mysqli_fetch_row($result);
    $count=$row[0];
    $_SESSION['sess_var']=$name;

    if($count > 0) {
        echo "<h1>$name,欢迎回来!</h1>
              <P>页面将在3秒后跳转.</p>";
        echo '<meta http-equiv="refresh" content="3; url=edit.php">';
    }else{
        //visitor`s name and password combination are not correct
        echo "You need to enter a correct name and password.";
    }
    }
?>
